//创建二维码界面
'use strict'
import React, { Component } from 'react';
import {
  View,
  TextInput,
  StyleSheet,
  TouchableOpacity,
  Text,
  Alert,
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import * as defaultStyles from '../constants/DefaultStyles';
import {Actions} from 'react-native-router-flux';
import ActionSheet from 'react-native-actionsheet';
import QRCode from 'react-native-qrcode-svg';
import { requestXML } from '../utils/RequestUtils';
import { json2xml_str } from '../utils/XmlUtils';
import Spinner from 'react-native-loading-spinner-overlay';

function removeThousand(str) {
  return str.replace(/,/g, '');
}

export default class CreateQRCodeContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
      amout: props.amout,
      QRCodeValue: props.QRCodeValue,
      title: props.title,
      paymentType: props.paymentType,
    };
  }
  _changePayment(type) {
    console.log(type);
    if (type === this.state.paymentType) {
      return;
    }
    if (type === '1') {
      this._getQRCode('alipay');
    }
    if (type === '2') {
      this._getQRCode('wechat');
    }


  }
  _handlePress(index) {
    this._changePayment(index.toString());
  }

  show() {
    this.ActionSheet.show();
  }

  _getQRCode(type) {
    let tanstype = '80014'
    if (type === 'alipay') {
      tanstype = '80008';
    }
    this.setState({isLoading: true});
    console.log(this.state.code);
    let xml = json2xml_str(JSON.stringify({
      Request: {
        Head: {
          trace_no: '6',
          terminalno: '8',
          acceptidcode: merid,
          tanstype: tanstype,
          operateno: '3'
        },
        Body: {
          SIGN: '122',
          amt: String(parseFloat(removeThousand(this.state.amout)) * 100)
        }}
    }));
    let respcd = '-1';
    const promise = requestXML('http://192.168.4.13:8084/icmp-ums/dhc/sys/mobile.do', xml, 15000);
    promise.then((object) => {
      console.log(object);
      let respcd = '-1';
      try {
        let Body = object.Response.Body;
        respcd = Body.respcd;
        if (respcd === '00') {
          this.setState({isLoading: false});
          if (type === 'wechat') {
            let QRValue = Body.code_url;
            console.log(QRValue);
            this.setState({
              QRCodeValue: QRValue,
              title: '微信支付收款',
              paymentType: '2',
            });
          }
          else if (type === 'alipay') {
            let QRValue = Body.qr_code;
            this.setState({
              QRCodeValue: QRValue,
              title: '支付宝收款',
              paymentType: '1',
            });
          }
        }
        else {
          Alert.alert('提示', '获取二维码失败', [{text: '确定', onPress: () => {this.setState({isLoading: false})}}]);
          return;
        }
      }
      catch (err) {
        Alert.alert('提示', '返回数据格式出错', [{text: '确定', onPress: () => {this.setState({isLoading: false})}}]);
      }
    }, (reject) => {
      Alert.alert('提示', '请求出错，请检查网络连接', [{text: '确定', onPress: () => {this.setState({isLoading: false})}}]);
    });
  }

  render() {
    let buttons = ['取消', '支付宝支付', '微信支付'];
    const CANCEL_INDEX = 0;
    const DESTRUCTIVE_INDEX = 1;
    return(
      <View style={styles.container}>
        <Spinner visible={this.state.isLoading} overlayColor={'rgba(0, 0, 0, 0.7)'}
                 textContent={this.state.textContent} textStyle={{color: 'white'}}/>
        <ActionSheet
          ref={(o) => this.ActionSheet = o}
          title="切换收款方式"
          options={buttons}
          cancelButtonIndex={CANCEL_INDEX}
          destructiveButtonIndex={DESTRUCTIVE_INDEX}
          onPress={this._handlePress.bind(this)}
        />
        <View style={styles.navBar}>
          <TouchableOpacity style={{flex: 1}} onPress={() => Actions.pop()}>
            <Icon name={'angle-left'} color={'white'} size={25} style={styles.searchBtn}/>
          </TouchableOpacity>
          <View style={styles.navBarTitle}>
            <Text style={{color: 'white', fontSize: 20, marginRight: 10}}>{this.state.title}</Text>
          </View>
          <TouchableOpacity style={{flex: 1, alignItems: 'flex-end'}}>
            <Icon name={'question-circle-o'} size={25} color="white" style={styles.navBarRightBtn}/>
          </TouchableOpacity>
        </View>
        <View style={styles.bottomView}>
          <View style={styles.QRCodeView}>
            <View style={styles.QRCodeAmout}>
              <Text style={{fontSize: 18, textAlign: 'center'}}>{'￥' + this.state.amout}</Text>
            </View>
            <View style={{flex: 4, justifyContent: 'center', alignItems: 'center'}}>
              {/*<QRCode*/}
                {/*value={this.state.QRCodeValue}*/}
                {/*size={200}*/}
                {/*bgColor='black'*/}
                {/*fgColor='white'*/}
              {/*/>*/}
              <QRCode
                value={this.state.QRCodeValue}
                size={210}
              />
            </View>
            <View style={styles.QRCodeChange}>
              <Text style={{fontSize: 16}}>{this.state.title + '，'}</Text>
              <TouchableOpacity onPress={() => this.show()}>
                <Text style={{color: defaultStyles.LIGHTBLUE, fontSize: 16}}>更换</Text>
              </TouchableOpacity>
            </View>
          </View>
          <View style={{marginTop: 50, justifyContent: 'center', alignItems: 'center'}}>
            <TouchableOpacity onPress={() => {
              let value = this.state.amout.replace(/,/, '');
              Actions.scanPage({amout: this.state.amout, value: value, type: 'replace'})
            }}>
              <Text style={{fontSize: 18, color: 'white'}}>切换至扫一扫收款</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  navBar: {
    flexDirection: 'row',
    height: defaultStyles.OS === 'ios' ? 64 : 44,
    backgroundColor: defaultStyles.LIGHTBLUE,
  },
  searchBtn: {
    marginTop: defaultStyles.OS === 'ios' ? 30 : 10,
    marginLeft: 10,
  },
  navBarTitle: {
    flex: 2,
    marginTop: defaultStyles.OS === 'ios' ? 30 : 10,
    alignItems: 'center',
  },
  navBarRightBtn: {
    flex: 1,
    marginTop: defaultStyles.OS === 'ios' ? 31 : 10,
    marginRight: 10
  },
  bottomView: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: defaultStyles.LIGHTBLUE,
  },
  QRCodeView: {
    marginTop: 20,
    backgroundColor: 'white',
    width: defaultStyles.SCREENWIDTH - 30,
    height: defaultStyles.SCREENWIDTH,
    borderRadius: 5,
  },
  QRCodeAmout: {
    flex: 1,
    borderBottomWidth: 0.5,
    borderBottomColor:'gray',
    justifyContent: 'center',
    alignItems: 'center'
  },
  QRCodeChange: {
    flex: 0.8,
    flexDirection: 'row',
    backgroundColor: defaultStyles.WHITEOFBACKGROUND,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 5,
  },
});